package main

import (
	"fmt"
	"sync"
	"time"
)

func f1(ch1 chan<- int) {
	defer wg1.Done()
	for i := 0; i < 100; i++ {
		ch1 <- i
	}
	close(ch1)
}
func f2(ch1 <-chan int, ch2 chan<- int) {
	defer wg1.Done()
	for {
		x, ok := <-ch1
		if !ok {
			break
		}
		ch2 <- x * x
	}
	close(ch2)
}

var wg1 sync.WaitGroup

func GoroutineTask() {
	a := make(chan int, 100)
	b := make(chan int, 100)
	wg1.Add(2)
	go f1(a)
	go f2(a, b)
	wg1.Wait()
	for x := range b {
		fmt.Println(x)
	}
}

func Worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Printf("worker %d starts job %d\n", id, j)
		time.Sleep(time.Second)
		fmt.Printf("worker %d finishes job %d\n", id, j)
		results <- j * 2
	}
}

func WorkPool() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)
	for w := 1; w <= 3; w++ {
		go Worker(w, jobs, results)
	}
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)
	for a := 1; a <= 5; a++ {
		<-results
	}
}
